
import 'package:simple_barcode_scanner/simple_barcode_scanner.dart' deferred as sbs;
import 'package:syria_sports/presentation/public_home_page/bloc/public_home_screen.dart';
import 'package:syria_sports/presentation/qr/qr_screen.dart';

import '../dashboard_container_screen/dashboard_container_screen.dart';
import 'bloc/login_bloc.dart';
import 'package:flutter/material.dart';
import 'package:syria_sports/core/app_export.dart';
import 'package:syria_sports/core/utils/validation_functions.dart';
import 'package:syria_sports/widgets/custom_elevated_button.dart';
import 'package:syria_sports/widgets/custom_outlined_button.dart';
import 'package:syria_sports/widgets/custom_text_form_field.dart';

class LoginScreen extends StatelessWidget {
  LoginScreen({Key? key}) : super(key: key);

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    mediaQueryData = MediaQuery.of(context);
    return SafeArea(
      child: Scaffold(
        //resizeToAvoidBottomInset: false,
        body: BlocProvider<LoginBloc>(
          create: (context) =>
              LoginBloc(LoginState())..add(LoginInitialEvent()),
          child: BlocConsumer<LoginBloc, LoginState>(
            listener: (context, state) {
              if (state.status == LoginStatus.success) {
                if(PrefUtils.isCoach()) {
                  Navigator.of(context, rootNavigator: true).pushAndRemoveUntil(MaterialPageRoute(builder: (context) =>
                      DashboardContainerScreen.builder(context)), (Route<dynamic> route) => false);
                } else {
                  Navigator.of(context, rootNavigator: true).pushAndRemoveUntil(MaterialPageRoute(builder: (context) =>
                const PublicHomeScreen()), (Route<dynamic> route) => false);
                }

              }
            },
            builder: (context, state) {

              var listWidgets = [
                Expanded(
                  flex: 1,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      _buildPageHeader(context),
                      SizedBox(height: 28.v),
                    ],
                  ),
                ),
                Expanded(
                  flex: 3,
                  child: Form(
                      key: _formKey,
                      child: SingleChildScrollView(
                        physics: const BouncingScrollPhysics(),
                        child: Container(
                            width: double.maxFinite,
                            constraints: BoxConstraints(
                                maxWidth: 100
                            ),
                            padding: EdgeInsets.only(left: 16.h, right: 16.h),
                            child: Column(children: [
                              BlocSelector<LoginBloc, LoginState,
                                  TextEditingController?>(
                                  selector: (state) => state.emailController,
                                  builder: (context, emailController) {
                                    return CustomTextFormField(
                                        controller: emailController,
                                        hintText: "ادخل اسم او رقم المستخدم",
                                        //autofocus: true,
                                        textInputType: TextInputType.emailAddress,
                                        prefix: Container(
                                            margin: EdgeInsets.fromLTRB(
                                                16.h, 12.v, 10.h, 12.v),
                                            child: CustomImageView(
                                                imagePath: ImageConstant.imgMail,
                                                height: 24.adaptSize,
                                                width: 24.adaptSize)),
                                        prefixConstraints:
                                        BoxConstraints(maxHeight: 48.v),
                                        validator: (value) {
                                          if (value == null ||
                                              (!isValidEmail(value,
                                                  isRequired: true))) {
                                            return "err_msg_please_enter_valid_email"
                                                .tr;
                                          }
                                          return null;
                                        },
                                        contentPadding: EdgeInsets.only(
                                            top: 15.v, right: 30.h, bottom: 15.v));
                                  }),
                              SizedBox(height: 10.v),
                              BlocSelector<LoginBloc, LoginState,
                                  TextEditingController?>(
                                  selector: (state) => state.passwordController,
                                  builder: (context, passwordController) {
                                    return CustomTextFormField(
                                        controller: passwordController,
                                        hintText: "lbl_password".tr,
                                        textInputAction: TextInputAction.done,
                                        textInputType: TextInputType.visiblePassword,
                                        maxLines: 1,
                                        prefix: Container(
                                            margin: EdgeInsets.fromLTRB(
                                                16.h, 12.v, 10.h, 12.v),
                                            child: CustomImageView(
                                                imagePath: ImageConstant.imgLock,
                                                height: 24.adaptSize,
                                                width: 24.adaptSize)),
                                        prefixConstraints:
                                        BoxConstraints(maxHeight: 48.v),
                                        validator: (value) {
                                          if (value == null ||
                                              (!isValidPassword(value,
                                                  isRequired: true))) {
                                            return "err_msg_please_enter_valid_password"
                                                .tr;
                                          }
                                          return null;
                                        },
                                        obscureText: true,
                                        contentPadding: EdgeInsets.only(
                                            top: 15.v, right: 30.h, bottom: 15.v));
                                  }),
                              SizedBox(height: 16.v),
                              BlocSelector<LoginBloc, LoginState, LoginStatus?>(
                                  selector: (state) => state.status,
                                  builder: (context, passwordController) {
                                    return CustomElevatedButton(
                                        text: state.status == LoginStatus.loading
                                            ? "lbl_sign_in_loading".tr
                                            : "lbl_sign_in".tr,
                                        buttonTextStyle: CustomTextStyles
                                            .titleSmallOnPrimaryContainer,
                                        onPressed: () {
                                          onTapSignIn(context);
                                        });
                                  }),
                              SizedBox(height: 18.v),
                              _buildOrLine(context),
                              /*SizedBox(height: 16.v),
                            CustomOutlinedButton(
                                text: " صور الباركود",
                                buttonTextStyle: theme.textTheme.titleMedium!
                                    .copyWith(color: Colors.red),
                                leftIcon: const Icon(
                                  Icons.qr_code_scanner,
                                  color: Colors.red,
                                ),
                                onPressed: () {
                                  onTapContinueAsGuest(context);
                                }),*/
                              SizedBox(height: 16.v),
                              CustomOutlinedButton(
                                  text: "المتابعة كضيف",
                                  buttonTextStyle: theme.textTheme.titleMedium!
                                      .copyWith(color: Colors.redAccent),
                                  onPressed: () {
                                    Navigator.of(context, rootNavigator: true).pushAndRemoveUntil(MaterialPageRoute(builder: (context) =>
                                    const PublicHomeScreen()), (Route<dynamic> route) => false);
                                  }),
                              /*Text("msg_forgot_password".tr,
                                style: CustomTextStyles.labelLargePrimary),
                            SizedBox(height: 7.v),*/
                            ])),
                      )),
                ),
              ];
              if(mediaQueryData.size.width>mediaQueryData.size.height){
                return Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: listWidgets,
                );
              }else {
                return Form(
                  key: _formKey,
                  child: SingleChildScrollView(
                    physics: const BouncingScrollPhysics(),
                    child: Container(
                        width: double.maxFinite,
                        padding: EdgeInsets.only(left: 16.h, top: 68.v, right: 16.h),
                        child: Column(
                            children: [
                          _buildPageHeader(context),
                          SizedBox(height: 28.v),
                          BlocSelector<LoginBloc, LoginState,
                                  TextEditingController?>(
                              selector: (state) => state.emailController,
                              builder: (context, emailController) {
                                return CustomTextFormField(
                                    controller: emailController,
                                    hintText: "ادخل اسم او رقم المستخدم",
                                    //autofocus: true,
                                    textInputType: TextInputType.emailAddress,
                                    prefix: Container(
                                        margin: EdgeInsets.fromLTRB(
                                            16.h, 12.v, 10.h, 12.v),
                                        child: CustomImageView(
                                            imagePath: ImageConstant.imgMail,
                                            height: 24.adaptSize,
                                            width: 24.adaptSize)),
                                    prefixConstraints:
                                        BoxConstraints(maxHeight: 48.v),
                                    validator: (value) {
                                      if (value == null ||
                                          (!isValidEmail(value,
                                              isRequired: true))) {
                                        return "err_msg_please_enter_valid_email"
                                            .tr;
                                      }
                                      return null;
                                    },
                                    contentPadding: EdgeInsets.only(
                                        top: 15.v, right: 30.h, bottom: 15.v));
                              }),
                          SizedBox(height: 10.v),
                          BlocSelector<LoginBloc, LoginState,
                                  TextEditingController?>(
                              selector: (state) => state.passwordController,
                              builder: (context, passwordController) {
                                return CustomTextFormField(
                                    controller: passwordController,
                                    hintText: "lbl_password".tr,
                                    textInputAction: TextInputAction.done,
                                    textInputType: TextInputType.visiblePassword,
                                    maxLines: 1,
                                    prefix: Container(
                                        margin: EdgeInsets.fromLTRB(
                                            16.h, 12.v, 10.h, 12.v),
                                        child: CustomImageView(
                                            imagePath: ImageConstant.imgLock,
                                            height: 24.adaptSize,
                                            width: 24.adaptSize)),
                                    prefixConstraints:
                                        BoxConstraints(maxHeight: 48.v),
                                    validator: (value) {
                                      if (value == null ||
                                          (!isValidPassword(value,
                                              isRequired: true))) {
                                        return "err_msg_please_enter_valid_password"
                                            .tr;
                                      }
                                      return null;
                                    },
                                    obscureText: true,
                                    contentPadding: EdgeInsets.only(
                                        top: 15.v, right: 30.h, bottom: 15.v));
                              }),
                          SizedBox(height: 16.v),
                          BlocSelector<LoginBloc, LoginState, LoginStatus?>(
                              selector: (state) => state.status,
                              builder: (context, passwordController) {
                                return CustomElevatedButton(
                                    text: state.status == LoginStatus.loading
                                        ? "lbl_sign_in_loading".tr
                                        : "lbl_sign_in".tr,
                                    buttonTextStyle: CustomTextStyles
                                        .titleSmallOnPrimaryContainer,
                                    onPressed: () {
                                      onTapSignIn(context);
                                    });
                              }),
                          SizedBox(height: 18.v),
                          _buildOrLine(context),
                          /*SizedBox(height: 16.v),
                          CustomOutlinedButton(
                              text: " صور الباركود",
                              buttonTextStyle: theme.textTheme.titleMedium!
                                  .copyWith(color: Colors.red),
                              leftIcon: const Icon(
                                Icons.qr_code_scanner,
                                color: Colors.red,
                              ),
                              onPressed: () {
                                onTapContinueAsGuest(context);
                              }),*/
                          SizedBox(height: 16.v),
                          CustomOutlinedButton(
                              text: "المتابعة كضيف",
                              buttonTextStyle: theme.textTheme.titleMedium!
                                  .copyWith(color: Colors.redAccent),
                              onPressed: () {
                                Navigator.of(context, rootNavigator: true).pushAndRemoveUntil(MaterialPageRoute(builder: (context) =>
                                    const PublicHomeScreen()), (Route<dynamic> route) => false);
                              }),
                          /*Text("msg_forgot_password".tr,
                              style: CustomTextStyles.labelLargePrimary),
                          SizedBox(height: 7.v),*/
                        ])),
                  ));
              }
            },
          ),
        ),
      ),
    );
  }

  /// Section Widget
  Widget _buildPageHeader(BuildContext context) {
    return Column(children: [
      CustomImageView(imagePath: ImageConstant.icLogo,height: 164.v,),
      SizedBox(height: 16.v),
      Text("msg_welcome_to_e_com".tr, style: theme.textTheme.titleMedium),
      SizedBox(height: 10.v),
      Text("msg_sign_in_to_continue".tr, style: theme.textTheme.bodySmall!.copyWith(color: Colors.red))
    ]);
  }

  /// Section Widget
  Widget _buildOrLine(BuildContext context) {
    return Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
      Expanded(
        child: Padding(
            padding: EdgeInsets.only(top: 10.v, bottom: 9.v),
            child: SizedBox( child: const Divider())),
      ),
      Text("lbl_or".tr, style: CustomTextStyles.titleMedium_1),
      Expanded(
        child: Padding(
            padding: EdgeInsets.only(top: 10.v, bottom: 9.v),
            child: SizedBox(child: const Divider())),
      )
    ]);
  }

  /// Navigates to the dashboardContainerScreen when the action is triggered.
  onTapSignIn(BuildContext context){
    FocusScope.of(context).unfocus();
    final cubit = context.read<LoginBloc>();
    cubit.add(LoginOnTapLoginEvent());
  }
  onTapContinueAsGuest(BuildContext context)async{
    FocusScope.of(context).unfocus();
    await sbs.loadLibrary();
      var res = await Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => sbs.SimpleBarcodeScannerPage(isShowFlashIcon: true,),
          ));
        if (res is String && res != "-1") {
          FocusScope.of(context).unfocus();
          final cubit = context.read<LoginBloc>();
          cubit.state.barcode = res;
          cubit.add(LoginOnTapLoginEvent());
        }

    /*Navigator.push(context, MaterialPageRoute(builder: (context1) => QRScreen(
       onBarcodeDetected: (value){
         FocusScope.of(context).unfocus();
         final cubit = context.read<LoginBloc>();
         cubit.state.barcode = value.value;
         cubit.add(LoginOnTapLoginEvent());
         Navigator.pop(context1);
       },
     ),
     ),
     );*/
    return;

  }
  /// Navigates to the registerScreen when the action is triggered.
  onTapTxtDoNotHaveAccount(BuildContext context) {

  }
}
